/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.jpa.impl;

import com.bifrost.jpa.DynamicQuery;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 *
 *
 *@author joewee
 *@version 1.0.0
 *@Date 2018/4/4 22:41
 */
@Repository
public class DynamicQueryImpl implements DynamicQuery {

    Logger logger = LoggerFactory.getLogger(DynamicQueryImpl.class);

    @PersistenceContext
    private EntityManager em;
    public EntityManager getEntityManager() {
        return em;
    }
    @Override
    public void save(Object entity) {
        em.persist(entity);
    }

    @Override
    public void update(Object entity) {
        em.merge(entity);
    }

    @Override
    public <T> void delete(Class<T> entityClass, Object entityid) {
        delete(entityClass, new Object[] { entityid });
    }

    @Override
    public <T> void delete(Class<T> entityClass, Object[] entityids) {
        for (Object id : entityids) {
            em.remove(em.getReference(entityClass, id));
        }
    }

    /**
     * 查询对象列表，返回List
     *
     * @param nativeSql
     * @param params
     * @return List<T>
     */
    @Override
    public <T> List<T> nativeQueryList(String nativeSql,boolean flag ,Object... params) {
        Query q = createNativeQuery(nativeSql,flag, params);
        q.unwrap(SQLQuery.class).setResultTransformer(Transformers.TO_LIST);
        return q.getResultList();
    }

    /**
     * 查询对象列表，返回List<Map<key,value>>
     *
     * @param nativeSql
     * @param params
     * @return List<T>
     */
    @Override
    public <T> List<T> nativeQueryListMap(String nativeSql, Object... params) {
        Query q = createNativeQuery(nativeSql, params);
        q.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return q.getResultList();
    }

    /**
     * 查询对象列表，返回List<组合对象>
     *
     * @param resultClass
     * @param nativeSql
     * @param params
     * @return List<T>
     */
    @Override
    public <T> List<T> nativeQueryListModel(Class<T> resultClass, String nativeSql, Object... params) {
        Query q = createNativeQuery(nativeSql, params);;
        q.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(resultClass));
        return q.getResultList();
    }
    private Query createNativeQuery(String sql, Object... params) {
        Query q = em.createNativeQuery(sql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                // 与Hiberante不同,jpa query从位置1开始
                q.setParameter(i + 1, params[i]);
            }
        }
        return q;
    }

    private Query createNativeQuery(String sql,boolean flag, Object... params) {
        Query q = em.createNativeQuery(sql);
        if (params != null && params.length > 0) {
            int index = 0;//記錄有幾個數據未被使用
            for (int i = 0; i < params.length; i++) {
                if(!flag) {
                    // 与Hiberante不同,jpa query从位置1开始
                    q.setParameter(i + 1, params[i]);
                }else{
                    if(params[i] != null){
                        q.setParameter(i + 1 - index, params[i]);
                    }else{
                        index ++;
                    }
                }
            }
        }
        return q;
    }
}
